//
//  PhotoBrowserViewController.swift
//  Tanenbaum_blog
//
//  Created by Tanenbaum on 15/8/9.
//  Copyright © 2015年 GZJ. All rights reserved.
//

import UIKit
import SVProgressHUD
let ZuoJPhotoBrowserCellID = "ZuoJPhotoBrowserCellID"
class PhotoBrowserViewController: UIViewController {

    
    //照片数组
    var urls:[NSURL]
    var selectedIndex: Int = 0

    init(urls: [NSURL],selectedIndex:Int){
        
        self.urls = urls
        self.selectedIndex = selectedIndex
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //监测一下是否拿到数据
    override func viewDidLoad() {
        
        print(urls)
        print(selectedIndex)
    }
    
    func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    func save() {
        
        let indexPath = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoBrowserViewCell
        
        guard let image = cell.imageView.image else {
            return
        }
        
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:" , nil)
        
    }
    func image(image: UIImage,didFinishSavingWithError error: NSError?,contextInfo: AnyObject?) {
        
        let msg = (error == nil) ? "保存成功" : "保存失败"
        
        SVProgressHUD.showInfoWithStatus(msg)
        
    }
    
    
    override func viewDidLayoutSubviews() {
        
        super.viewDidLayoutSubviews()
        
        let indexPath = NSIndexPath(forItem: selectedIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    override func loadView() {
        
        view = UIView(frame: UIScreen.mainScreen().bounds)
        setupUI()
    }
    
    private func setupUI() {
        
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        let dict = ["cv":collectionView,"save":saveButton,"close":closeButton]
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[save(32)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[close(32)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[close(100)]-(>=0)-[save(100)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
         closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
         saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
         prepareCollectionView()
        
    }
    
    private func prepareCollectionView() {
        
        collectionView.registerClass(PhotoBrowserViewCell.self, forCellWithReuseIdentifier: ZuoJPhotoBrowserCellID)
        collectionView.dataSource = self
        
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
       collectionView.pagingEnabled = true
       collectionView.showsHorizontalScrollIndicator = false
        
    }

    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 18, color: UIColor.whiteColor(), back: UIColor.darkGrayColor())
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 18, color: UIColor.whiteColor(), back: UIColor.darkGrayColor())
    private var photoScale: CGFloat = 1

}
extension PhotoBrowserViewController: UICollectionViewDataSource,PhotoBrowserCellDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
         let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ZuoJPhotoBrowserCellID, forIndexPath: indexPath) as! PhotoBrowserViewCell
        
         cell.backgroundColor = UIColor.randomColor()
         cell.imageURL = urls[indexPath.item]
         cell.photoDelegate = self
        return cell
    }
   
    func photoBrowserCellZoom(scale: CGFloat) {
        
        photoScale = scale
        hiddenControls(scale < 1)
        if scale < 1.0 {
            startInteractiveTransition(self)
        }else {
            view.transform = CGAffineTransformIdentity
            view.alpha = 1
        }
        
        
    }
    
    func currentImageView() ->UIImageView {
        
        let cell = collectionView.cellForItemAtIndexPath(currentImageIndex()) as! PhotoBrowserViewCell
        
        return cell.imageView
    }
    func currentImageIndex() ->NSIndexPath {
        
        return collectionView.indexPathsForVisibleItems().last!
    }
    private func hiddenControls(hidden:Bool) {
        collectionView.backgroundColor = hidden ? UIColor.clearColor() : UIColor.blackColor()
        closeButton.hidden = hidden
        saveButton.hidden = hidden
    }
    func photoBrowserCellEndZoom() {
        
        if photoScale < 0.8 {
            
            completeTransition(true)
        } else {
            
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                
                self.view.transform = CGAffineTransformIdentity
                self.view.alpha = 1
                }, completion: { (_) -> Void in
                    
                    self.photoScale = 1
                    self.hiddenControls(false)
            })
        }
    }
}
extension PhotoBrowserViewController:UIViewControllerInteractiveTransitioning {
    
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        view.transform = CGAffineTransformMakeScale(photoScale, photoScale)
        view.alpha = photoScale
    }
}
extension PhotoBrowserViewController: UIViewControllerContextTransitioning {
    
    
    func completeTransition(didComplete:Bool) {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func containerView() -> UIView? { return view.superview }
    func isAnimated() -> Bool { return true }
    
    func isInteractive() -> Bool { return true }
    
    func transitionWasCancelled() -> Bool { return false }
    
    func presentationStyle() -> UIModalPresentationStyle { return UIModalPresentationStyle.Custom }
    
    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition() { }
    func cancelInteractiveTransition() { }
    
//    func completeTransition(didComplete: Bool) { return false}
    
 
    func viewControllerForKey(key: String) -> UIViewController? { return self }

    func viewForKey(key: String) -> UIView? {return view}
    
    func targetTransform() -> CGAffineTransform { return CGAffineTransformIdentity}
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect {return CGRectZero}
    func finalFrameForViewController(vc: UIViewController) -> CGRect {return CGRectZero}

}
